package com.android.nodejs.livejs.activities;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.nodejs.livejs.MyApplication;
import com.android.nodejs.livejs.R;
import com.android.nodejs.livejs.adapters.ChatApdapter;
import com.android.nodejs.livejs.adapters.FriendAdapter;
import com.android.nodejs.livejs.constants.AddMessageConstants;
import com.android.nodejs.livejs.constants.DisplayConstants;
import com.android.nodejs.livejs.models.Chat;
import com.android.nodejs.livejs.models.User;
import com.android.nodejs.livejs.utils.CommonUtil;

public class ChatActivity extends Activity implements OnClickListener {

    private ListView mListView;
    private ListView lvUserForAddToGroup;
    private FriendAdapter friendAdapter;
    private ChatApdapter mChatApdater;

    private User me;
    private User friend;
    private EditText mEdtChat;
    private Button btnSend;
    private TextView tvTextTitle;

    private BufferedWriter w;
    private String txtChat;
    private int idGroup;
    private int idSender;
    private String friendFullName;
    private String friendAvatar;
    private int idS; // nhan tu server gui ve moi lan co tin nhan
    private String nameS;// nhan tu server gui ve moi lan co tin nhan

    private ArrayList<Chat> chatHistory = new ArrayList<Chat>();
    private List<User> listUserForAddToGroup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        // register broad cast
        IntentFilter filterMessageChat = new IntentFilter("MESSAGE_CHAT_ITEM");
        this.registerReceiver(new MessageBroadCastReceiver(), filterMessageChat);
        initComponents();
        addListener();
        initData();
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    private void initComponents() {
        idGroup = getIntent().getExtras().getInt("group_id");
        idSender = getIntent().getExtras().getInt("sender_id");
        friendFullName = getIntent().getExtras().getString("friend_full_name");
        friendAvatar = getIntent().getExtras().getString("friend_avatar");
        w = new BufferedWriter(new OutputStreamWriter(MyApplication.OS_CURRENT));
        mListView = (ListView) findViewById(R.id.listview);
        mEdtChat = (EditText) findViewById(R.id.edt_chat);
        btnSend = (Button) findViewById(R.id.bt_send);
        tvTextTitle = (TextView) findViewById(R.id.tvTextTitle);
        tvTextTitle.setText(friendFullName);
        tvTextTitle.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                //Toast.makeText(getApplicationContext(), tvTextTitle.getText().toString().trim(), Toast.LENGTH_LONG).show();
                CommonUtil.dialogNotify(ChatActivity.this, tvTextTitle.getText().toString().trim());
            }
        });
        // set isRunning = true
        if(idGroup != 0) {
            MyApplication.IS_RUNNING.put(String.valueOf(idGroup), true);
        } else {
            MyApplication.IS_RUNNING.put(String.valueOf(MyApplication.GROUP_ID), true);
        }
        // set list user for add to group chat
         listUserForAddToGroup = (List) ((ArrayList) MyApplication.LIST_FRIENDS).clone();
         
    }

    @SuppressWarnings("unchecked")
    private void initData() {
        me = MyApplication.USER_CURRENT;
        friend = new User(idSender, friendFullName, friendAvatar);
        mChatApdater = new ChatApdapter(this, chatHistory);
        if (getIntent().getExtras().getSerializable("list_msgs") != null) {
            List<String> listMessage = (List<String>) getIntent().getExtras().getSerializable("list_msgs");
            List<String> listTime = (List<String>) getIntent().getExtras().getSerializable("list_times");
            // set message chat fragment to chat activity
            for (int i = 0; i < listMessage.size(); i++) {
                mChatApdater.add(new Chat(1, friend, listMessage.get(i), listTime.get(i)));
                mChatApdater.notifyDataSetChanged();
                mListView.setSelection(mChatApdater.getCount() - 1);
            }
        }
        mListView.setAdapter(mChatApdater);
        mListView.setSelection(mChatApdater.getCount() - 1);
    }

    /** Show Toast message */
    private Handler toastHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                if(idS != idSender) {
                    idSender = idS;
                    friendFullName = nameS;
                    friend = new User(idSender, friendFullName, friendAvatar);
                }
                mChatApdater.add(new Chat(1, friend, txtChat, CommonUtil.getSysTime()));
                mChatApdater.notifyDataSetChanged();
                mListView.setSelection(mChatApdater.getCount() - 1);
            } else if (msg.what == 1) {
                Toast.makeText(getApplicationContext(), DisplayConstants.DIS_SEND_MSG_FAIL, Toast.LENGTH_LONG).show();
            } else if (msg.what == 2) {
                // nothing...
            }
        }
    };

    @Override
    protected void onStop() {
        super.onStop();
        MyApplication.IS_RUNNING.put(String.valueOf(idGroup), false);
        MyApplication.IS_RUNNING.put(String.valueOf(MyApplication.GROUP_ID), false);
    }

    private void addListener() {
        btnSend.setOnClickListener(this);
    }

    public void onClick(View v) {
        String text = mEdtChat.getText().toString().trim();
        if (text.length() > 0) {
            mChatApdater.add(new Chat(0, me, text, CommonUtil.getSysTime()));
            mChatApdater.notifyDataSetChanged();
            mListView.setSelection(mChatApdater.getCount() - 1);
            mEdtChat.setText("");
            // chat
            try {
                // write: id A!!name A!!id B!!text!!date time
                w.write(AddMessageConstants.CHAT);
                w.write(MyApplication.USER_CURRENT.getId() + "!!" + MyApplication.USER_CURRENT.getFullName() + "!!"
                        + ((idGroup!=0)?idGroup:MyApplication.GROUP_ID) + "!!" + text + "!!" + CommonUtil.getSysDateTime());
                w.flush();
            } catch (IOException e) {
                Log.d("IOException", e.getClass().getSimpleName() + ": " + e.getMessage());
                e.printStackTrace();
            }
        }
    }

    public void onClickBack(View v) {
        setResult(RESULT_CANCELED);
        finish();
    }

    public void onClickAddToGroup(View v) {
        for (int element : MyApplication.LIST_ID_EACH_GROUP.get((idGroup!=0)?idGroup:Integer.parseInt(MyApplication.GROUP_ID))) {
            for (int i = 0; i < listUserForAddToGroup.size(); i++) {
                if (listUserForAddToGroup.get(i).getId() == element) {
                    listUserForAddToGroup.remove(i);
                }
            }
        }
        AlertDialog.Builder builderSingle = new AlertDialog.Builder(this);
        builderSingle.setTitle("Select One Name");
        //final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.select_dialog_singlechoice);
        final FriendAdapter arrayAdapter = new FriendAdapter(ChatActivity.this, listUserForAddToGroup);
        builderSingle.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                int idUser = arrayAdapter.getItem(which).getId();
                if (idUser == idGroup) {
                    Toast.makeText(getApplicationContext(), "This user already exists!", Toast.LENGTH_LONG).show();
                } else {
                    try {
                        w.write(AddMessageConstants.ADD_TO_GROUP);
                        w.write(AddMessageConstants.HAVE_GROUP + MyApplication.GROUP_ID + "!!" + idUser);
                        w.flush();
                        // notify
                        String nameUser = arrayAdapter.getItem(which).getFullName();
                        AlertDialog.Builder builderInner = new AlertDialog.Builder(ChatActivity.this);
                        builderInner.setMessage("Added " + nameUser + " successful!");
                        builderInner.setTitle("Done");
                        builderInner.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        builderInner.show();
                        // add title
                        tvTextTitle.setText(tvTextTitle.getText().toString()+", "+ nameUser);
                        //remove this user in list user
                        listUserForAddToGroup.remove(which);
                    } catch (IOException e) {
                        Log.d("IOException", e.getClass().getSimpleName() + ": " + e.getMessage());
                        e.printStackTrace();
                    }
                }
            }
        });
        builderSingle.show();
    }

    /**
     * send message broadcast
     * 
     * @author vuvt
     * 
     */
    private class MessageBroadCastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ("MESSAGE_CHAT_ITEM".equals(intent.getAction())) {
                int num = Integer.parseInt(intent.getStringExtra("what"));
                if (num == 0) {
                    txtChat = intent.getStringExtra("msg");
                    idS = Integer.parseInt(intent.getStringExtra("idSender"));
                    nameS = intent.getStringExtra("nameSender");
                }
                Message msg = toastHandler.obtainMessage(num);
                toastHandler.sendMessage(msg);
            }
        }
    }
}
